package cn.itcast.bos.service.base.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.itcast.bos.dao.base.CourierRepository;
import cn.itcast.bos.dao.base.FixedAreaRepository;
import cn.itcast.bos.dao.base.TakeTimeRepository;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.TakeTime;
import cn.itcast.bos.service.base.FixedAreaService;
@Service
@Transactional
public class FixedAreaServiceImpl implements FixedAreaService {

	@Autowired
	private FixedAreaRepository fixedAreaRepository;
	@Autowired
	private CourierRepository courierRepository;
	@Autowired
	private TakeTimeRepository takeTimeRepository;
	
	@Override
	public void add(FixedArea model) {
		fixedAreaRepository.save(model);
	}
	@Override
	public Page<FixedArea> pageQuery(Specification<FixedArea> specification, Pageable pageable) {
		
		return fixedAreaRepository.findAll(specification, pageable);
	}
	@Override
	public void associationCourierToFixedArea(FixedArea fixedArea, Integer courierId, Integer takeTimeId) {
		//利用持久化对象具有修改数据库的能力,来完成对数据库的修改		
		
		//通过定区id找到相应的定区
		FixedArea _fixedArea = fixedAreaRepository.findOne(fixedArea.getId());
		//通过快递员id找到相对于的快递员
		Courier courier = courierRepository.findOne(courierId);
		//通过收派时间id找到相对应的收派时间
		TakeTime takeTime = takeTimeRepository.findOne(takeTimeId);
		
		//将快递员关联定区(外键的维护权利在定区,由定区添加快递员)
		_fixedArea.getCouriers().add(courier);
		
		//将收派时间关联快递员(外键的维护权利在快递员,由快递员来保存收派时间)
		courier.setTakeTime(takeTime);
	}
	@Override
	public void del(String idsStr) {
		String[] ids = idsStr.split("-");
		for (String id : ids) {
			fixedAreaRepository.delete(id);
		}
	}
	@Override
	public FixedArea findOne(String id) {
		return fixedAreaRepository.findOne(id);
	}
	@Override
	public List<FixedArea> findAll() {
		
		return fixedAreaRepository.findAll();
	}

}
